<template>
    <div class="head">
        <van-nav-bar
            title="购物车"
            left-arrow>
            <template #right>
                <div class="control" @click="controlEvt">{{ isEdit ? '完成' : '管理'}} </div>
            </template>
            <template #left>
                <div class="adds" @click="router.push('/address')">成都市武侯区肖家河沿街</div>
            </template>
        </van-nav-bar>
    </div>
    <div class="cont">
        <div class="cart-box">
            <Item v-for="it in cart_list" 
            :key="it.id" :it="it"
            @btnEvt="cartBtnEvt"
            ></Item>
        </div>
        
        <div class="recm">
            <p>猜你喜欢</p>
            <div class="shop">
                <div v-for="it in list " :key="it.id">
                    <img :src="baseURL + `${it.path} `" alt="">
                    <p class="title">{{ it.title }}</p>
                    <p class="price">￥{{ it.price }}</p>
                </div>
            </div>
        </div>
    </div>
    <div class="pay">
        <van-checkbox checked-color="#92da76" v-model="checkAll">全选</van-checkbox>
        <p class="price">总价:<span>￥{{ amount }}</span></p>
        <p class="toPay" @click="submitEvt">{{isEdit ? '删除' : '结算'}}({{ total }})</p>
    </div>
</template>

<script lang="ts" setup>
import {  computed, ref, Ref,WritableComputedRef } from "vue";
import { useRouter } from "vue-router";
import Item from "./item.vue";
import {  getHomeProductsApi } from "../../apis/productApis";
import { cartDeleteApi, cartModifyApi, getCartListApi, orderAddApi } from "../../apis/cartApis";
import { useCommonStore } from "../../store";
import { showConfirmDialog, showToast } from "vant";

const router = useRouter()
const baseURL = window.baseURL
const list:Ref<Array<any>> = ref([])
const cart_list:Ref<Array<any>> = ref([])

getList()
async function getList() {
    let _res = await getHomeProductsApi(3,6)
    // console.log(_res)
    if(_res.code === 200){
        list.value = _res.data.rows
    }
}

// 获取购物车数据
const uid: string = useCommonStore().userInfo.id;
getCartList()
async function getCartList() {
    let _res = await getCartListApi(uid)
    if(_res.code === 200){
        cart_list.value = _res.data.map((it:any)=>{
            it.checked = false
            return it
        })
    }
    // console.log(_res.data);
    
}
/**添加或减少按钮的点击事件 */
async function  cartBtnEvt(id:string,type:string) {
    let item = cart_list.value.find((it:any)=>it.id == id) as any;
    let obj = {
        userId:uid,
        id,
        count:0
    }
    let next = false;
    if(type == 'add'){
        obj.count = item.count * 1 + 1;
        next = true
    }else{
        if(item.count <= 1){
            showConfirmDialog({
                title:'确认删除',
                message:'确定不考虑一下？'
            }).then(async()=>{
                let _ret = await cartDeleteApi({userId:uid,ids:[id+'']});
                if(_ret.code == 200){
                    cart_list.value.splice(cart_list.value.findIndex((it:any)=>it.id==id),1);
                }
            }).catch(()=>{})
        }else{
            next=true;
            obj.count = item.count*1 -1
        }
    }
    if(!next) return;
    let _res = await cartModifyApi(obj);
    if(_res.code == 200){
        item.count = obj.count
    }
}

// 全选和单选功能;计算钩子函数
const checkAll:WritableComputedRef<boolean> = computed({
    get(){
        return cart_list.value.every(it => it.checked)
    },
    set(val){
        cart_list.value.map((it:any)=>it.checked = val)
    }
})

/**累计金额 */
const amount:WritableComputedRef<number>=computed(()=>{
    return cart_list.value.reduce((r:number,it:any)=>{
        if(it.checked) r += it.price * it.count
        return r
    },0)
})
// 累计数量
const total:WritableComputedRef<number>=computed(()=>{
    return cart_list.value.reduce((r:number,it:any)=>{
        if(it.checked) r +=  it.count*1
        return r
    },0)
})

// 管理按钮
const isEdit:Ref<boolean> = ref(false)
function controlEvt(){
    isEdit.value = !isEdit.value
}

// 结算按钮和删除按钮
async function  submitEvt() {
    let _list = JSON.parse(JSON.stringify(cart_list.value.filter((it:any)=>it.checked))).map((oo:any)=>{
        delete oo.checked;
        oo.userId = uid;
        return oo;
    })
    if(!isEdit.value){
        let _res = await orderAddApi({
            "userId":uid,
            'list':_list
        })
        if(_res.code == 200){
            showToast('提交订单成功')
            getCartList()
        }
    }else{
        let ids = _list.map((it:any)=>it.id)
        let _ret = await cartDeleteApi({userId:uid,ids});
        if(_ret.code == 200){
            cart_list.value = cart_list.value.filter((oo:any)=>!ids.includes(oo.id))
        }
    }
}
</script>

<style lang="less" scoped>
@import url('../../style/comon.less');

.head{
    .van-nav-bar{
        border-bottom: 1px solid #e6e6e6;
    }
}
.cont{
    height: calc(100% - 46px - 16vh);
    background-color: #fff;
    margin: .4rem;
    overflow-x: hidden;
    background-color: @g1;
    .cart-box{
        width: 100%;
        min-height: 50vh;
        margin-bottom: 1rem
    }
    .recm{
        min-height: 40vh;
        background-color: #fff;
        border-radius: 1rem;
        >p{
            text-align: center;
            font-size: .8rem;
            line-height: 2.4rem;
            border-bottom: 1px solid #bcbcbc;
        }
        .shop{
            display: flex;
            flex-wrap: wrap;
            padding-top: .4rem;
            div{
                width: calc(100% / 2);
                text-align: center;
                img{
                    width: 8rem;
                    height: 8rem;
                }
                .title{
                    font-size: .75rem;
                    line-height: 1.6rem;
                    width: 100%;
                    padding: 0 .4rem;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
                .price{
                    font-size: .75rem;
                    color: @b1;
                    line-height: 1.6rem;
                }
            }
            
        }
    }
}
.pay{
    width: 100%;
    height: 8vh;
    line-height: 8vh;
    background-color: #fffbfb;
    position: fixed;
    bottom: 8vh;
    display: flex;
    .van-checkbox{
        margin-left: .8rem;
        font-size: .7rem;
    }
    .price{
        font-size: .7rem;
        font-weight: bold;
        text-align: right;
        padding-right: 1rem;
        flex: 1;
        span{
            color: @b1;
            font-size: .85rem;
            font-weight: 400;
        }
    }
    .toPay{
        text-align: center;
        width: 8rem;
        height: 8vh;
        background-color: @g6;
        font-size: .8rem;
        color: #fff1f1;
    }
}

::v-deep .adds{
    width: 4.5rem;
    font-size: .75rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
::v-deep .control{
    font-size: .8rem;
}

</style>



